'use strict';

const _ = require('lodash');
const path = require('path');
const fs = require('fs');
const events = require('events');
const config = require('./config');
const logger = require('log4js').getLogger();

const THREAD = config.thread || 8;

const Application = module.exports = function (m3u8File) {
	this.uploader = require('./plugin/' + config.cdn)();
	this.m3u8 = m3u8File;
	this.dirname = path.dirname(m3u8File);
	this.lines = [];
	
	this.line_pos = 0;
	this.line_count = 0;
	this.initialize();
	this.event = new events.EventEmitter();
	this.event.on('start_upload', this.startUpload.bind(this));
};

Application.prototype.initialize = function () {
	const str = fs.readFileSync(this.m3u8, 'utf8');
	this.lines = _.split(str, '\n');
};

Application.prototype.callBack = function (line_pos, uploadUrl) {
	if (!uploadUrl) return logger.error('Upload error: line', line_pos + 1);
	this.lines[line_pos] = uploadUrl;
	logger.log('Uploaded: line', line_pos + 1);
};

Application.prototype.startUpload = function () {
	if (!this.uploader.isOK) return logger.error('Uploader: not isOK !!!');
	const length = this.lines.length;
	if (this.line_pos >= length && this.line_count <= 0) {
		if (this.uploader.processList) this.uploader.processList(this.lines);
		const m3u8Path = this.dirname + '/uploaded.m3u8';
		return fs.writeFileSync(m3u8Path, this.lines.join('\n'), 'utf8');
	}
	for (; this.line_pos < length && this.line_count < THREAD; ++this.line_pos) {
		const line_pos = this.line_pos;
		const line = this.lines[line_pos].trim();
		if (!line || line.charAt(0) == '#') continue;
		if (/^https?:\/\//.test(line)) continue;
		const filePath = this.dirname + '/' + line;
		this.line_count += 1;
		logger.log('Uploading: line', line_pos + 1, line);
		this.uploader.uploadFile(filePath, (err, data) => {
			if (err) logger.error(filePath, err);
			else this.callBack(line_pos, this.uploader.parseNewUrl(data, filePath));
			if (this.line_count > 0) this.line_count -= 1;
			if (this.line_count < THREAD) this.event.emit('start_upload');
		});
	}
};

if (require.main === module) (function () {
	const m3u8File = process.argv[2];
	if (!m3u8File) return logger.error('Missing m3u8File !!!');
	const app = new Application(m3u8File);
	return app.startUpload();
})();

